package com.x.control;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.x.service.transactional.ProjectService;

@Controller
@RequestMapping("/project")
public class ProjectController {

	@Autowired(required = true)
	ProjectService projectService;

	String[] columns = { "name", "description", "type", "province", "city",
			"district" };

	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request) {
		int startIndex = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String draw = request.getParameter("draw");

		List<String[]> odrerPart = new ArrayList<>();
		List<String[]> wherePart = new ArrayList<>();

		for (int i = 0; i < columns.length; i++) {
			String orderColumn = request.getParameter("order[" + i
					+ "][column]");
			if (orderColumn != null) {
				String orderDir = request.getParameter("order[" + i + "][dir]");
				odrerPart.add(new String[] {
						columns[Integer.parseInt(orderColumn)], orderDir });
			}
		}
		for (int i = 0; i < columns.length; i++) {
			String searchable = request.getParameter("columns[" + i
					+ "][searchable]");
			if (searchable.equals("true")) {
				String searchColumn = columns[i];
				String value = request.getParameter("columns[" + i
						+ "][search][value]");
				if (!value.isEmpty()) {
					wherePart.add(new String[] { searchColumn, value });
				}
			}
		}

		Map<String, Object> result = projectService.list(startIndex, length,
				wherePart, odrerPart);
		result.put("draw", draw);
		return result;
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	ModelAndView create(@RequestParam("name") String name,
			@RequestParam("description") String description,
			@RequestParam("type") String type,
			@RequestParam("district") String district) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("nav", "project");
		mv.setViewName("home");
		if (!projectService.create(name,description,type, district)) {
			mv.addObject("error", "create location fail: Duplicate Projects!");
		}
		return mv;
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	String delete(@RequestParam("id") String id) {
		projectService.delete(id);
		return "redirect:/home/project";
	}
}
